/**

 @Name: 用户模块

 */
 
layui.define(['laypage', 'fly', 'element', 'flow', 'table'], function(exports){

  var $ = layui.jquery;
  var layer = layui.layer;
  var util = layui.util;
  var laytpl = layui.laytpl;
  var form = layui.form;
  var laypage = layui.laypage;
  var fly = layui.fly;
  var flow = layui.flow;
  var element = layui.element;
  var upload = layui.upload;
  var table = layui.table;

  //我发的贴
  if($('#LAY_mySendCard')[0]){
	  var uid=$('#LAY_mySendCard').data("uid");
	  table.render({
	    elem: '#LAY_mySendCard'
	    ,url: '/article/list'
	    ,method: 'post'
    	,where: {
    		author:uid
	    }
	    ,cols: [[
	      {field: 'title', title: '帖子标题', minWidth: 200, templet: '<div><a href="/article/detail/{{ d.id }}/" target="_blank" class="layui-table-link">{{ d.title }}</a></div>'}
	      ,{field: 'status', title: '状态', width: 100, align: 'center', templet: function(d){
	        if(d.status == 9){
	          return '<span style="color: #5FB878;">已结</span>';
	        } else if(d.status == 0){
	          return '<span style="color: #ccc;">审核中</span>';
	        } else {
	          return '<span style="color: #ccc;">未结</span>'
	        }
	      }}
	      ,{field: 'rec', title: '加精', width: 100, align: 'center', templet: function(d){
	    	  return d.rec ? '<span style="color: #FF5722;">是</span>' : ''
	      }}
	      ,{field: 'top', title: '置顶', width: 100, align: 'center', templet: function(d){
	    	  return d.top ? '<span style="color: #FF5722;">是</span>' : ''
	      }}
	      ,{field: 'createTime', title: '发表时间', width: 120, align: 'center', templet: '<div>{{ layui.util.timeAgo(d.createTime, 1) }}</div>'}
	      ,{title: '数据', width: 150, templet: '<div><span style="font-size: 12px;">{{d.views}}阅/{{d.comment}}答</span></div>'}
	      ,{title: '操作', width: 100, templet: function(d){
	        return d.status != 9 ? '<a class="layui-btn layui-btn-xs" href="/safe/article/edit/'+ d.id +'" target="_blank">编辑</a>' : ''
	      }}
	    ]]
	    ,page: true
	    ,skin: 'line'
	  });
  }
  

  //我收藏的帖
  if($('#LAY_myCollectioncard')[0]){
	  table.render({
	    elem: '#LAY_myCollectioncard'
	    ,url:'/safe/collect/list'
	    ,method: 'post'
    	,where: {
    		orderByColumn:'createTime',
    		isAsc:'desc'
	    }
	    ,cols: [[
	      {field: 'title', title: '帖子标题', minWidth: 300, templet: '<div><a href="/article/detail/{{ d.artId }}/" target="_blank" class="layui-table-link">{{ d.title }}</a></div>'}
	      ,{title: '收藏时间', width: 120, align: 'center', templet: '<div>{{ layui.util.timeAgo(d.createTime, 1) }}</div>'}
	    ]]
	    ,page: true
	    ,skin: 'line'
	  });
  }
  
  //最近发帖
  var tplRenjie = ['{{# layui.each(d.rows, function(index, item){ }}'
	    ,'<li>'
	    ,'{{# if(item.rec) { }}'
	      ,'<span class="fly-jing">精</span>'
	    ,'{{# } }}'
	        ,'<a href="/article/detail/{{item.id}}" class="jie-title">{{item.title}}</a>'
	        ,'<i>{{layui.util.timeAgo(item.createTime,1)}}</i>'
	        ,'<em class="layui-hide-xs">{{item.views}}阅/{{item.comment}}答</em>'
	    ,'</li>'
	  ,'{{# }); }}'].join('')
	  ,recentlyJie = $('#recently-jie');

  if(recentlyJie[0]){
	  var uid = recentlyJie.data('uid');
	  fly.json('/article/list/',{author:uid,pageNum:1,pageSize:10}, function(res){
		  if(res.rows.length>0){
			  var html = laytpl(tplRenjie).render(res);
			  recentlyJie.html(html);
		  }
	  });
  }
  //最近回答
  var tplRenda = ['{{# layui.each(d.rows, function(index, item){ }}'
	    ,'<li>'
	    ,'<p>'
	      ,'<span>{{layui.util.timeAgo(item.createTime,1)}}</span>在<a href="/article/detail/{{item.artId}}" target="_blank">{{item.artTitle}}</a>中回答：'
	    ,'</p>'
	        ,'<div class="home-dacontent">'
	        ,'{{item.content}}'
	        ,'</div>'
	    ,'</li>'
	  ,'{{# }); }}'].join('')
	  
	  ,recentlyDa = $('#recently-jieda');
  if(recentlyDa[0]){
	  var uid = recentlyDa.data('uid');
	  fly.json('/comment/list/',{author:uid,pageNum:1,pageSize:10}, function(res){
		  if(res.rows.length>0){
			  var html = laytpl(tplRenda).render(res);
			  recentlyDa.html(html);
		  }
	  });
  }

  //显示当前tab
  if(location.hash){
    element.tabChange('user', location.hash.replace(/^#/, ''));
  }

  element.on('tab(user)', function(){
    var othis = $(this), layid = othis.attr('lay-id');
    if(layid){
      location.hash = layid;
    }
  });


  var gather = {}, dom = {
    mine: $('#LAY_mine')
    ,mineview: $('.mine-view')
    ,minemsg: $('#LAY_minemsg')
    ,infobtn: $('#LAY_btninfo')
  };

  //根据ip获取城市
/*  if($('#L_city').val() === ''){
    $.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(){
      $('#L_city').val(remote_ip_info.city||'');
    });
  }*/
  
  // 修改用户信息
  form.on('submit(userInfo)', function(data){
	  $.ajax({
	      type: 'post',
	      url: '/safe/user/info/edit',
	      data: data.field,
	      dataType: 'json',
	      success: function (data) {
	      	if(data.code==0){
	      		location.reload();
	      	}else{
		        layer.msg(data.msg, {icon: 2});
	      	}
	      }
	  });
	  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
  });
  // 修改用户信息
  form.on('submit(repass)', function(data){
	  $.ajax({
		  type: 'post',
		  url: '/safe/user/repass',
		  data: data.field,
		  dataType: 'json',
		  success: function (data) {
			  if(data.code==0){
				  layer.msg(data.msg, {icon: 1});
				  form.val("repass",{
					  nowpass:'',
					  newpass:'',
					  repass:'',
				  })
			  }else{
				  layer.msg(data.msg, {icon: 2});
			  }
		  }
	  });
	  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
  });

  //上传图片
  if($('.upload-img')[0]){
    layui.use('upload', function(upload){
      var avatarAdd = $('.avatar-add');
      upload.render({
        elem: '.upload-img'
        ,url: '/safe/user/upload/'
        ,size: 50
        ,before: function(){
          avatarAdd.find('.loading').show();
        }
        ,done: function(res){
          if(res.code == 0){
              layer.msg("保存成功,正在刷新数据请稍后……", {
                      icon: 1,
                      time: 500,
                      shade: [0.1, '#8F8F8F']
                  },
                  function() {
                      location.reload();
                  });
          } else {
            layer.msg(res.msg, {icon: 5});
          }
          avatarAdd.find('.loading').hide();
        }
        ,error: function(){
          avatarAdd.find('.loading').hide();
        }
      });
    });
  }

  //提交成功后刷新
  fly.form['set-mine'] = function(data, required){
    layer.msg('修改成功', {
      icon: 1
      ,time: 1000
      ,shade: 0.1
    }, function(){
      location.reload();
    });
  }

  //帐号绑定
  $('.acc-unbind').on('click', function(){
    var othis = $(this), type = othis.attr('type');
    layer.confirm('确定要解绑'+ ({
      qq_id: 'QQ'
      ,weibo_id: '微博'
    })[type] + '吗？', {icon: 5}, function(){
      fly.json('/api/unbind', {
        type: type
      }, function(res){
        if(res.status === 0){
          layer.alert('已成功解绑。', {
            icon: 1
            ,end: function(){
              location.reload();
            }
          });
        } else {
          layer.msg(res.msg);
        }
      });
    });
  });


  //我的消息
  gather.minemsg = function(){
    var delAll = $('#LAY_delallmsg')
    ,tpl = '{{# var len = d.rows.length;\
    if(len === 0){ }}\
      <div class="fly-none">您暂时没有最新消息</div>\
    {{# } else { }}\
      <ul class="mine-msg">\
      {{# for(var i = 0; i < len; i++){ }}\
        <li data-id="{{d.rows[i].id}}">\
          <blockquote class="layui-elem-quote">{{ d.rows[i].content}}</blockquote>\
          <p><span>{{d.rows[i].time}}</span><a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-danger fly-delete">删除</a></p>\
        </li>\
      {{# } }}\
      </ul>\
    {{# } }}'
    ,delEnd = function(clear){
      if(clear || dom.minemsg.find('.mine-msg li').length === 0){
        dom.minemsg.html('<div class="fly-none">您暂时没有最新消息</div>');
      }
    }
    
    
    /*fly.json('/message/find/', {}, function(res){
      var html = laytpl(tpl).render(res);
      dom.minemsg.html(html);
      if(res.rows.length > 0){
        delAll.removeClass('layui-hide');
      }
    });*/
    
    //阅读后删除
    dom.minemsg.on('click', '.mine-msg li .fly-delete', function(){
      var othis = $(this).parents('li'), id = othis.data('id');
      fly.json('/message/remove/', {
        id: id
      }, function(res){
        if(res.status === 0){
          othis.remove();
          delEnd();
        }
      });
    });

    //删除全部
    $('#LAY_delallmsg').on('click', function(){
      var othis = $(this);
      layer.confirm('确定清空吗？', function(index){
        fly.json('/message/remove/', {
          all: true
        }, function(res){
          if(res.status === 0){
            layer.close(index);
            othis.addClass('layui-hide');
            delEnd(true);
          }
        });
      });
    });

  };

  dom.minemsg[0] && gather.minemsg();




 


  exports('user', {});
  
});